package com.example.takeaway.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.plugins.pagination.PageDTO;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.takeaway.common.ResponseEnum;
import com.example.takeaway.context.UserInfoContext;
import com.example.takeaway.converter.CategoryConverter;
import com.example.takeaway.exception.BusException;
import com.example.takeaway.mapper.CategoryMapper;
import com.example.takeaway.model.PageVO;
import com.example.takeaway.model.bo.Category;
import com.example.takeaway.model.dto.CategoryDTO;
import com.example.takeaway.model.dto.CategoryEditorDTO;
import com.example.takeaway.model.vo.CategoryVO;
import com.example.takeaway.service.CategoryService;
import javafx.util.Pair;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 分类表 服务实现类
 * </p>
 *
 * @author 邢晨旭
 * @since 2023-10-12
 */
@Service
public class CategoryServiceImpl extends ServiceImpl<CategoryMapper, Category> implements CategoryService {

    @Resource
    CategoryMapper categoryMapper;

    @Resource
    CategoryConverter categoryConverter;

    @Override
    public void saveCategory(CategoryDTO param) {
        //分类名称是否已存在
        Integer count = categoryMapper.queryByName(param.getCategoryName(), param.getShopId());
        if (count > 0) {
            throw new BusException(ResponseEnum.CATEGORY_EXIST);
        }
        Category category = categoryConverter.toCategory(param);
        categoryMapper.insert(category);
    }

    @Override
    public void updateCategory(CategoryEditorDTO param) {
        Category oldCategory = categoryMapper.queryById(param.getId());
        if (oldCategory == null) {
            throw new BusException(ResponseEnum.CATEGORY_NOT_EXIST);
        }
        if (oldCategory.getStatus() == 1) {
            throw new BusException(ResponseEnum.CATEGORY_STATUS_ERROR);
        }
        Integer count = categoryMapper.queryByIdAndName(param);
        if (count > 0) {
            throw new BusException(ResponseEnum.CATEGORY_EXIST);
        }
        Category category = categoryConverter.toCategory(param);
        categoryMapper.updateById(category);
    }

    @Override
    public Map<Integer, List<String>> deleteCategoryByIds(List<Long> ids) {
        //根据ids查询所有的分类信息
        List<Category> categoryList = categoryMapper.selectBatchIds(ids);
        Map<Long, Category> categoryMap = categoryList.stream().collect(Collectors.toMap(Category::getId, category -> category));
        //查询分类下是否有关联的菜品
        List<Pair<Long, Integer>> dishCountPairs = categoryMapper.selectDishCountBatchIds(ids);
        Map<Long, Integer> dishCountMap = dishCountPairs.stream().collect(Collectors.toMap(Pair::getKey, Pair::getValue));
        //收集分类数据中的状态为1的分类名字
        List<String> result1 = new ArrayList<>();
        List<String> result2 = new ArrayList<>();
        List<Long> deleteIds = new ArrayList<>();
        ids.forEach(id -> {
            Category category = categoryMap.get(id);
            //分类启用,不能删除
            if (category.getStatus() == 1) {
                result1.add(category.getCategoryName());
                return;
            }
            //分类下有关联的菜品不能删除
            if (dishCountMap.get(id) != null && dishCountMap.get(id) > 0) {
                result2.add(category.getCategoryName());
                return;
            }
            deleteIds.add(id);
        });
        if (deleteIds.size() > 0) {
            categoryMapper.deleteByBatchIds(deleteIds);
        }
        Map<Integer, List<String>> result = new HashMap<>(2);
        result.put(1, result1);
        result.put(2, result2);
        return result;
    }

    @Override
    public CategoryVO queryById(Long id) {
        LambdaQueryWrapper<Category> wrapper = Wrappers.lambdaQuery();
        wrapper.eq(Category::getId, id)
                .eq(Category::getIsDeleted, 0);
        Category category = categoryMapper.selectOne(wrapper);
        if (category == null) {
            throw new BusException(ResponseEnum.CATEGORY_NOT_EXIST);
        }
        return categoryConverter.toCategoryVO(category);
    }

    @Override
    public PageVO<CategoryVO> queryPage(Integer page, Integer size) {
        Page<Category> pageDTO = PageDTO.of(page, size);
        List<Category> list = baseMapper.queryPage(pageDTO, UserInfoContext.get().getUserId());
        PageVO<CategoryVO> pageVO = new PageVO<>();
        pageVO.setPage(page);
        pageVO.setSize(size);
        pageVO.setTotal(pageDTO.getTotal());
        pageVO.setList(categoryConverter.toCategoryVO(list));
        return pageVO;
    }

    @Override
    public List<CategoryVO> queryList() {
        return baseMapper.queryList(UserInfoContext.get().getUserId(), null);
    }

    @Override
    public List<CategoryVO> queryList(Long shopId) {
        return baseMapper.queryList(shopId, 1);
    }


}
